/*
 * indexed_log.h
 *
 *  Created on: 17-May-2011
 *      Author: tan-ce
 */

#ifndef INDEXED_LOG_H_
#define INDEXED_LOG_H_

#include <string>
#include <cstdio>
#include <exception>

class IndexedLog {
protected:
	typedef struct {
		time_t timestamp;
		long offset;
		size_t len;
	} index_entry;

	FILE *idx;
	FILE *log;


	void append_idx_record(index_entry *rec) {
		// Seek not necessary because file is opened with mode "a+"
		fwrite(rec, sizeof(index_entry), 1, idx);
	}
public:
	IndexedLog(const char *name);
	void append_log(std::string msg);

	// Returns the actual number of lines returned back in linecount
	std::string retrieve_logs(long record, size_t *linecount);
	long last_rec() {
		fseek(idx, 0, SEEK_END);
		return (ftell(idx) / sizeof(index_entry)) - 1;
	}
};

class IndexedLogError : public std::exception {
protected:
	const char *msg;

public:
	IndexedLogError(const char *msg) {
		this->msg = msg;
	}

	virtual ~IndexedLogError() throw() {}

	virtual const char* what() const throw() {
		return msg;
	}
};

#endif /* INDEXED_LOG_H_ */
